import { Injectable } from "@angular/core";
import * as showdown from "showdown";
import * as $ from "jquery";

@Injectable({
  providedIn: "root"
})
export class IndexService {
  node: any = "";
  constructor() {
    this.node = "";
  }

  // 生成html文本
  giftFormat(qArray, theDiv) {
    this.node = "";
    var _this = this;
    var converter: any;
    return new Promise((resolve, reject) => {
      converter = new showdown.Converter();
      let html = "";
      let q;
      for (let i = 0; i < qArray.length; i++) {
        // console.log("i = " + i + " and qArray[i] is '" + qArray[i] );
        q = qArray[i];
        html += '<div id="question_' + i + '">';
        // console.log("q.type is '" + q.type );
        switch (q.type) {
          case "Description":
            html += makeTitle("Description", q.title);
            html += "<p>" + applyFormat(q.stem) + "</p>";
            _this.node = _this.node + html;
            html = "";
            break;
          case "MC":
            html += makeTitle("Multiple choice", q.title);
            html += "<p>" + applyFormat(q.stem) + "</p>";
            html += formatAnswers(q.choices);
            html += formatFeedback(q.globalFeedback) + "</div>";
            console.log(html, "html MC");
            _this.node = _this.node + html;
            html = "";
            break;
          case "Short":
            html += makeTitle("Short answer", q.title);
            html += "<p>" + applyFormat(q.stem) + "</p>";
            html += formatAnswers(q.choices);
            html += formatFeedback(q.globalFeedback) + "</div>";
            _this.node = _this.node + html;
            html = "";
            break;
          case "Essay":
            html += makeTitle("Essay", q.title);
            html += "<p>" + applyFormat(q.stem) + "</p>";
            html += formatFeedback(q.globalFeedback) + "</div>";
            _this.node = _this.node + html;
            html = "";
            // html += formatAnswers(q.choices);
            break;
          case "TF":
            html += makeTitle("True/False", q.title);
            html +=
              "<p>" +
              "<em>(" +
              (q.isTrue ? "True" : "False") +
              ")</em> " +
              applyFormat(q.stem) +
              "</p>";
            html += formatFeedback(q.globalFeedback) + "</div>";
            _this.node = _this.node + html;
            html = "";
            // html += formatAnswers(q.choices);
            break;
          case "Matching":
            html += makeTitle("Matching", q.title);
            html += "<p>" + applyFormat(q.stem) + "</p>";
            //                theDiv.append(html); html = "";
            formatMatchingAnswers(q, theDiv, i, html);
            html = formatFeedback(q.globalFeedback) + "</div>";
            _this.node = _this.node + html;
            html = "";
            break;
          // for case "Matching": see https://stackoverflow.com/a/35493737/1168342
          default:
            break;
        }
      }
      resolve(_this.node);
    });

    function makeTitle(type, title) {
      return "<b>" + type + (title !== null ? ' "' + title + '"' : "") + "</b>";
    }
    function ResultZm() {
      let result = [];
      for (let i = 0; i < 26; i++) {
        result.push(String.fromCharCode(65 + i));
      }
      return result;
    }
    function formatAnswers(choices) {
      // 生成字母
      const result = ResultZm();
      let html = "<ul>";
      for (let a = 0; a < choices.length; a++) {
        let answer = choices[a];
        answer.text.text = `${result[a]}: ${answer.text.text}`;
        html +=
          '<li class="' +
          (answer.isCorrect ? "rightAnswer" : "wrongAnswer") +
          '">' +
          (answer.weight !== null ? "<em>(" + answer.weight + "%)</em> " : "") +
          applyFormat(answer.text) +
          (answer.feedback !== null
            ? " [" + applyFormat(answer.feedback) + "]"
            : "") +
          "</li>";
      }
      html += "</ul>";
      return html;
    }

    function formatMatchingAnswers(q, theDiv, qNum, html) {
      let rightSideChoices = new Set();
      //    let html ='';
      let htmlLines = "";
      for (let i = 0; i < q.matchPairs.length; i++) {
        htmlLines +=
          '<path id="line' +
          i +
          '" stroke="rgba(180,180,255,0.5)" stroke-width="5" fill="none"/>';
      }
      html +=
        '<svg class="theSVG" style="position: absolute; z-index: -1;" width="100%" height="100%" z-index="-1"><g>' +
        htmlLines +
        "</g></svg>";

      html += '<div class="row"><div class="col-md-6">'; // left side
      for (let i = 0; i < q.matchPairs.length; i++) {
        let pair = q.matchPairs[i];
        html += '<div id="left' + i + '" style="background:#ddddff">';
        html += "<p>" + applyFormat(pair.subquestion) + "</p>";
        //        html += applyFormat(pair.subquestion);
        html += "</div>";
        rightSideChoices.add(pair.subanswer);
      }
      console.log("Found rightSideChoices: " + rightSideChoices.size);
      html += "</div>";

      html += '<div class="col-md-6">'; // right side
      for (
        let it = rightSideChoices.values(), val = null;
        (val = it.next().value);

      ) {
        //console.log('answer: ' + val);
        html +=
          '<div id="right_' +
          val.replace(/\s/g, "_") +
          '" style="background:#ddddff">';
        html += "<p>" + val + "</p>";
        //        html += val;
        html += "</div>";
      }
      html += "</div></div>";
      // make the SVG for lines, see https://stackoverflow.com/a/35493737/1168342
      _this.node = _this.node + html;
      html = ""; // force the HTML into the DOM

      // set the lines up - search only inside this question's div (theDiv)
      for (let i = 0; i < q.matchPairs.length; i++) {
        const ref = document.getElementById("question_" + qNum);
        console.log(ref, "ref");
        let qDiv = $("#question_" + qNum);
        let pair = q.matchPairs[i];
        let line = qDiv.find("#line" + i);
        console.log("line: " + line);
        let leftDiv = qDiv.find("#left" + i);
        console.log("leftDiv: " + leftDiv);
        let rightDiv = qDiv.find(
          "#right_" + pair.subanswer.replace(/\s/g, "_")
        );
        console.log("rightDiv: " + rightDiv);
        let pos1 = leftDiv.offset();
        let pos2 = rightDiv.offset();
        let svg = qDiv.find(".theSVG").offset();
        // line
        //   .attr('x1', pos1.left - svg.left + leftDiv.width())
        //   .attr('y1', pos1.top + leftDiv.height()/2 - svg.top)
        //   .attr('x2', pos2.left - svg.left)
        //   .attr('y2', pos2.top + rightDiv.height()/2 - svg.top);
        let x1 = pos1.left - svg.left + leftDiv.width();
        let y1 = pos1.top + leftDiv.height() / 2 - svg.top;
        let x2 = pos2.left - svg.left;
        let y2 = pos2.top + rightDiv.height() / 2 - svg.top;
        let inset = 10;
        line.attr(
          "d",
          "M" +
            x1 +
            "," +
            y1 +
            " C" +
            (x1 + inset) +
            "," +
            y1 +
            " " +
            (x2 - inset) +
            "," +
            y2 +
            " " +
            x2 +
            "," +
            y2
        );
        qDiv
          .find(".theSVG")
          .attr("height", pos1.top + leftDiv.height() - svg.top);
      }
      // return html;
    }

    function applyFormat(giftText) {
      console.log(giftText, "text");
      // console.log("applyFormat: " + giftText.format + " to " + giftText.text);
      let html = "";
      switch (giftText.format) {
        case "moodle":
        case "plain":
        case "html":
          html = giftText.text;
          console.log(html, "html");
          break;

        case "markdown":
          html = converter.makeHtml(giftText.text);
          break;

        default:
          break;
      }
      if (html == "") html = "&nbsp;"; // special case so div's aren't empty
      return html;
    }

    function formatFeedback(feedback) {
      return feedback !== null
        ? '<p style="margin-left: 40px"><em>General feedback:</em> ' +
            applyFormat(feedback) +
            "</p>"
        : "";
    }
  }
}
